<?php

namespace App\Business\BLL\Wechat;

use App\Business\BLL\Wechat\Official;
use App\Models\WechatUser;

class OfficialEvent
{
    public function receiveEvent($message)
    {
        $official = Official::make();
        $res = "";
        switch ($message['Event']) {
            case 'subscribe':
                //用户写入数据库
                $user = $official->user->get($message['FromUserName']);
                $wechatUser = WechatUser::firstOrCreate(
                    [
                        'unionid' => $user['unionid'],
                    ]
                    , [
                        'wechat_openid' => $user['openid'],
                        'name' => $user['nickname'],
                        'head_img' => $user['headimgurl'],
                    ]
                );
                if (empty($wechatUser->wechat_openid)) {
                    $wechatUser->wechat_openid = $user['openid'];
                    $wechatUser->save();
                }
                //关注欢迎语
                $res = "大侠，欢迎闯荡乒乓江湖，点击左下角乒乓江湖按钮，即可开启江湖生涯。线上约战，线下一键PK,门派之争、擂台赛事、江湖纷争，更多好玩有趣，尽在乒乓江湖！";
                break;
            case 'unsubscribe':
                //取关
                $user = $official->user->get($message['FromUserName']);
                $wechatUser = WechatUser::where('wechat_openid', $user['openid'])->first();
                $wechatUser->wechat_openid = null;
                $wechatUser->save();

                break;
            default:
                //其他
                $res = "";
                break;
        }

        return $res;
    }
}
